package com.pwser.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice //全局捕获异常
public class GlobalExceptionHandler {
	
	private static Logger logger = Logger.getLogger(GlobalExceptionHandler.class);
	
//	/**
//	 *  全局异常返回Json
//	 * @param request
//	 * @param ex
//	 * @return
//	 */
//	@ResponseBody
//	@ExceptionHandler(Exception.class)
//	ResponseEntity<Map<String, Object>> handleControllerException(HttpServletRequest request, Throwable ex) {
//		HttpStatus status = getStatus(request);
//		Map<String, Object> map = new HashMap<String, Object>();
//	    //状态码
//        map.put("status", status.value());
//	    //标识失败
//	    map.put("flag", "error");
//	    //异常信息
//	    map.put("message", ex.getMessage());
// 		logger.error(e.getMessage(), e);
//
//		return new ResponseEntity<Map<String, Object>>(map, status);
//	}
//
//	private HttpStatus getStatus(HttpServletRequest request) {
//		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
//		if (statusCode == null) {
//			return HttpStatus.INTERNAL_SERVER_ERROR;
//		}
//		return HttpStatus.valueOf(statusCode);
//	}
	
	/**
	 * 全局异常返回统一界面
	 * @param request
	 * @param e
	 * @return
	 */
	@ExceptionHandler(Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) {
        ModelAndView mav = new ModelAndView("global");
        mav.addObject("exception", e);
        mav.addObject("url", request.getRequestURL());
        logger.error(e.getMessage(), e);
        return mav;
    }

}
